var mosca = require('mosca')
var { log2File, trimFile } = require('../utils/logutils')
var ascoltatore = {
  //using ascoltatore
  //type: 'mongo',
  //url: 'mongodb://localhost:27017/mqtt',
  //pubsubCollection: 'ascoltatori',
  //mongo: {}
}

var settings = {
  port: 1883,
  backend: ascoltatore
}

var server = new mosca.Server(settings)

const androidClient = {}

server.authenticate = (client, username, password, callback) => {
  if ('server_123456' === client.id) {
    if (
      'server_123456_username' === username &&
      'server_123456_password' === password.toString('utf8')
    ) {
      callback(null, true)
      client.handleSubscribe({
        qos: 1,
        subscriptions: [
          {
            topic: 'deviceInfo',
            qos: 1
          },
          {
            topic: 'com.yoogor.app_s',
            qos: 1
          }
        ],
        messageId: server.nextDedupId()
      })
    } else {
      callback(null, false)
    }
    return
  }
  callback(null, true)
}

server.on('clientConnected', function(client) {
  console.log('client connected', client.id)
})

server.on('clientDisconnected', function(client) {
  console.log('clientDisconnected', client.id)
  if (androidClient[client.id]) {
    let file = `${androidClient[client.id].udid}_${
      androidClient[client.id].package
    }`
    trimFile(file)
  }
  delete androidClient[client.id]
})

server.on('clientError', function(e, client) {
  console.log('client error', e)
  if (androidClient[client.id]) {
    let file = `${androidClient[client.id].udid}_${
      androidClient[client.id].package
    }`
    trimFile(file)
  }
  delete androidClient[client.id]
})

// fired when a message is received
server.on('published', function(packet, client) {
  if (packet.topic === 'deviceInfo') {
    try {
      const deviceInfo = JSON.parse(packet.payload.toString())
      for (var key in client.subscriptions) {
        client.handleAuthorizeSubscribe(
          null,
          true,
          {
            topic: deviceInfo.package + key,
            qos: client.subscriptions[key].qos
          },
          () => {}
        )
      }
      androidClient[client.id] = deviceInfo
      client.subscriptions['com.yoogor.app_s'].handler(
        'com.yoogor.app_s',
        JSON.stringify({
          hello: 'world'
        }),
        {}
      )
    } catch (error) {
      console.log(error)
    }
  }
  if (client && androidClient[client.id]) {
    let file = `${androidClient[client.id].udid}_${
      androidClient[client.id].package
    }`
    log2File(file, packet.topic + '\t' + packet.payload.toString())
  }
})

server.on('subscribed', function(topic, client) {
  if ('server_123456' === topic && 'server_123456' !== client.id) {
    client.close()
  }
})

server.on('ready', setup)

// fired when the mqtt server is ready
function setup() {
  console.log('Mosca server is up and running')
}

var mqtt = require('mqtt')
var client = mqtt.connect('mqtt://localhost', {
  clientId: 'server_123456',
  username: 'server_123456_username',
  password: 'server_123456_password'
})

client.on('connect', function() {
  client.subscribe('server_123456')
})

client.on('error', function(err) {
  console.log(err.message)
})

client.on('message', function(topic, message) {
  // message is Buffer
  console.log(topic, message.toString())
})

const getClients = () => {
  return androidClient
}

module.exports = { getClients }
